import { Component, Injectable, Injector, OnInit, Input } from '@angular/core';
import { Validators } from '@angular/forms';
import * as _ from 'lodash';
import { differenceInCalendarDays } from 'date-fns';
import { UniversalFunctionsUtil } from '../../../core/universal-functions.util';
import { timeout } from 'rxjs/operators';
import { _HttpClient } from '@delon/theme';
import { StamonthplanService } from './statmonthplan.service';
import { environment } from '../../../../environments/environment';

@Injectable({ providedIn: 'root' })

@Component({
  selector: 'app-statmonthplan-table',
  templateUrl: './statmonthplan.table.component.html',
  styleUrls: ['./statmonthplan.table.component.less']
})
export class StatmonthplanTableComponent extends UniversalFunctionsUtil implements OnInit {
  data: any[];
  today: Date = new Date();
  expandDataCache: { orgid?: string } = {};
  modalVisible = false;
  loadingDetail = true;
  detailData: any[];
  lockHeadScroll = { x: '2000px', y: window.innerHeight - 350 + 'px' };
  lockHeadScroll2 = { y: window.innerHeight - 350 + 'px' };
  orgtype = '';
  detailScroll = { y: '60vh' };
  @Input() user;
  @Input() set inputParam(v) {
    this.validateForm = this.fb.group({
      monthPicker: [null, [Validators.required]]
    });
    this.orgtype = v.orgtype || '';
    this.query();
  }

  ngOnInit() {

  }

  constructor(
    private injector: Injector,
    private stamonthplanService: StamonthplanService,
    private http: _HttpClient
  ) {
    super(injector);
  }

  collapse(array, data, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.norder == d.norder);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  private visitNode(node, hashMap: object, array): void {
    if (!hashMap[node.norder]) {
      hashMap[node.norder] = true;
      array.push(node);
    }
  }

  private convertTreeToList(root: object) {
    const stack = [];
    const array = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: false });
    while (stack.length) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level + 1, expand: false, parent: node });
        }
      }
    }
    return array;
  }

  private getStatistics(year: number = this.today.getFullYear(),
    month: number = this.today.getMonth() + 1): void {
    this.monthStatisticsTable(year, month)
      .subscribe(res => {
        if (_.isArray(res)) {
          this.data = res;
          this.loadingData = false;
          this.data.forEach(item => {
            this.expandDataCache[item.orgid] = this.convertTreeToList(item);
          });
        }
      }, err => this.errorHandle(err));
  }
  // 月计划统计表单
  monthStatisticsTable(nYear: number, nMonth: number) {
    const url = environment.apiBase + '/csmis/ymVwaMonthplan/getmonthstatistics.jwt';
    return this.http.get(url, { nYear, nMonth });
  }

  query() {
    // const userType = this.user.userType;
    const typeCfg = {
      gq: '0',
      cj: '1',
      dd: '2',
    }
    const param = {
      nYear: this.today.getFullYear(),
      nMonth: this.today.getMonth() + 1,
      vcCj: typeCfg[this.orgtype],
    };
    if (this.validateForm.value.monthPicker) {
      const currDate = new Date(this.validateForm.value.monthPicker);
      param.nYear = currDate.getFullYear();
      param.nMonth = currDate.getMonth() + 1;
    }
    this.stamonthplanService.queryTj(param).subscribe(res => {
      if (_.isArray(res)) {
        this.data = res;
        this.loadingData = false;
        this.data.forEach(item => {
          this.expandDataCache[item.orgid] = this.convertTreeToList(item);
        });
      }
    }, err => this.errorHandle(err));
  }

  submitForm(): void {
    const currDate = new Date(this.validateForm.value.monthPicker);
    this.getStatistics(currDate.getFullYear(), currDate.getMonth() + 1);
  }

  disabledDate = (current: Date): boolean => {
    // Can not select days before today and today
    return differenceInCalendarDays(current, this.today) > 0 ||
      differenceInCalendarDays(current, new Date(2016, 0)) < 0;
  }

  scanDetails(evt, data, type: number) {
    evt.preventDefault();
    const vcCjObj = {
      gq: '0',
      cj: '1',
      dd: '2',
    }
    const params: any = {};
    this.modalVisible = true;
    params.org = data.orgid;
    params.parOrg = data.porgid;
    params.yearStr = data.years;
    params.monthStr = data.months;
    params.mtype = type;
    params.vcCj = vcCjObj[this.orgtype];
    this.monthStatisticsDetail(params)
      .pipe(timeout(2500))
      .subscribe(res => {
        if (_.isArray(res)) {
          this.detailData = res;
          this.loadingDetail = false;
        }
      }, err => (this.errorHandle(err), this.loadingDetail = false));
  }

  // 月计划统计明细数据
  monthStatisticsDetail(params) {
    const url = environment.apiBase + '/csmis/ymVwaMonthplan/monthstatdetail.jwt';
    return this.http.get(url, params);
  }

}
